<?php

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class discuz_ftp_oss{

	var $config = array();
	var $enabled = 1;
	var $connectid;
	var $error = 0;
	var $files = '';
	var $filesize = 0;
	var $file;
	var $filedata = array();
	var $file_acl = 0; //附件权限 0=公共读 1=完全私有,需授权
	var $Content_md5 = '';
	var $file_contents = '';
	
	function &instance($attachdata) {
		static $object;
		if(empty($object)) {
			$object = new discuz_ftp_oss($attachdata);
		}
		return $object;
	}

	function __construct($attachdata) {
		$this->error = 0;
		$config = getglobal('setting/ftp');
		
		if(empty($config['on']) || $config['on'] !='2' || empty($config['ftp_oss_host']) || empty($config['ftp_oss_type'])) {
			$this->error = 1;
		} else {
			$this->config = array();
			$this->config['type'] = $this->clear($config['ftp_oss_type']);
			$this->config['host'] = $this->clear($config['ftp_oss_host']);
			$this->config['id'] = $this->clear($config['ftp_oss_id']);
			$this->config['key'] = $this->clear($config['ftp_oss_key']);
			$this->config['bucket'] = $this->clear($config['ftp_oss_bucket']);
			$this->config['dir'] = $this->clear($config['ftp_oss_dir']);
			$this->config['timeout'] = 30;
			$this->connectid = intval($this->config['type']);
			if($attachdata && is_array($attachdata)){
				$this->filedata = $attachdata;
			}
		}
		
	}
	
	function upload($file, $filename) {	
		if($this->config['type'] == '1'){
			return $this->upload_Aliyun($file, $filename);
		}
		return false;
	}
	
	function auth($mod, $file, $gmdate,$Content_Type,$extend_sign=array()){
		if($this->config['type'] == '1'){
			return $this->auth_Aliyun($mod, $file, $gmdate,$Content_Type,$extend_sign);
		}
	}
	
	function get_file_url($file){
		if($this->config['type'] == '1'){
			$data = $this->auth('GET',$file,TIMESTAMP+10,'');
			$host = getglobal('setting/ftp/attachurl');
			if(!$host){
				$host = $this->config['host'];
			}
			$data['durls'] = $host.$data['url'].'?OSSAccessKeyId='.urlencode($data['id']).'&Expires='.$data['date'].'&Signature='.urlencode($data['token']);
			return $host.$data['url'].'?OSSAccessKeyId='.urlencode($data['id']).'&Expires='.$data['date'].'&Signature='.urlencode($data['token']);
		}
		return '';
	}
	
	function ftp_delete($path) {
		if($this->config['type'] == '1'){
			return $this->ftp_delete_Aliyun($path);
		}
		return false;
	}
	function ftp_size($remote_file) {
		$remote_file = $this->clear($remote_file);
		if($this->config['type'] == '1'){
			return $this->ftp_size_Aliyun($remote_file);
		}
		return 0;
	}
	
	/* 阿里云OSS接口定义
 	 * 
	 */
	function auth_Aliyun($mod, $file, $gmdate,$Content_Type,$extend_sign=array()){
		global $_G;
		if($this->error || !$this->config['host']) {
			$this->error = 1;
			return array();
		}
		
		if(!$mod || !$file){
			$this->error = 1;
			return array();
		}
		
		$ext = fileext($file);
		$Content_Type = isset($Content_Type) ? $Content_Type : $this->get_mime($ext);
		$this->files = str_replace(array(DISCUZ_ROOT.'./',DISCUZ_ROOT,$_G['setting']['attachdir'],$_G['setting']['attachurl'],'data/attachment/'),array('','','','',''),$file);
		$this->files = trim($this->files,'/');
		
		$file = $this->files;
		$gmdate = $gmdate ? $gmdate : gmdate('D, d M Y H:i:s \G\M\T');
		if($this->config['dir']){
			$file = $this->config['dir'].$file;
		}
		$upload_file = $file;
		$url = $this->config['host'].$file;
		$file = '/'.$this->config['bucket'].'/'.$file;
		
		$this->file_contents = file_get_contents(getglobal('setting/attachdir').$this->files);
		$signature = array($mod,$this->Content_md5,$Content_Type,$gmdate);
		if($extend_sign){
			foreach($extend_sign as $value){
				$signature[] = $value;
			}
		}
		$signature[] = $file;
		$signature_data = $signature;
		
		$signature = base64_encode(hash_hmac('sha1',implode("\n",$signature), $this->config['key'], true));
		return array(
			'mod' => $mod,
			'token' => $signature,
			'date' => $gmdate,
			'signdata' => $signature_data,
			'bucket' => $this->config['bucket'],
			'host' => $this->config['host'],
			'id' => $this->config['id'],
			'Content_Type' => $Content_Type,
			'ext' => $ext,
			'file' => $this->files,
			'url' => $upload_file,
			'ossurl' => $this->config['host'].$upload_file,
		);
	}
	
	function upload_Aliyun($file, $filename) {
		
		if($this->error) {
			return false;
		}
		if(strpos($file,'thumb.jpg')){
			$this->filedata = array();
		}
		//如果从外部传入了uoload附件数据，则优先使用外部数据
		if($this->filedata && $this->filedata['size']){
			$this->filesize = $this->filedata['size'];
			if($this->filedata['extension'] =='attach'){
				//如果是论坛私有附件，则上传时需要定义该文件权限
				$this->file_acl = 1;
			}
		}
		$data = $this->auth('PUT',$file,'',$this->get_mime(fileext($filename)),($this->file_acl ? array('x-oss-object-acl:private') : ''));
		if(!$data) return false;
		
		$this->filesize = filesize(getglobal('setting/attachdir').$data['file']);
		if(!$this->filesize){
			return false;
		}
		$this->file = fopen(getglobal('setting/attachdir').$data['file'], 'r');
		$headers = array(
			'Content-Type: '.$data['Content_Type'],
			'Content-Length: '.$this->filesize,
			'Date: '.$data['date'],
			'Authorization: OSS '.$data['id'].':'.$data['token'],
			'Cache-Control:'.(86400*30),
		);
		if($this->Content_md5){
			$headers[] = 'Content-MD5: '.$this->Content_md5;
		}
		
		if($this->file_acl){ //私有附件
			if($filename){
				$headers[] = 'Content-Disposition: attachment;filename='.urlencode($filename);
			}
			$headers[] = 'x-oss-object-acl: private';
		}
		$data = $this->Aliyun_curl($data['ossurl'],'PUT',$headers,$this->file_contents);
		$this->filedata = array();
		$this->file = $this->files = $this->Content_md5 = $this->file_contents = '';
		
		if($data['status']['http_code'] =='200' && $data['status']['upload_content_length'] == $this->filesize){
			return true;
		}else{
			return false;
		}
	}
	
	function ftp_size_Aliyun($file){
		if($this->error) {
			return 0;
		}
		$data = $this->auth('HEAD',$file,'','application/x-www-form-urlencoded');
		
		$headers = array(
			'Content-Type: application/x-www-form-urlencoded',
			'Authorization: OSS '.$data['id'].':'.$data['token'],
			'Date: '.$data['date'],
		);
		$data = $this->Aliyun_curl($data['ossurl'],'HEAD',$headers,5);
		if($data && $data['status']['http_code'] =='200'){
			return $data['status']['download_content_length'];
		}
		return 0;
	}
	
	function ftp_delete_Aliyun($file){
		//成功返回传入的 $Bucket
		if($this->error) {
			return false;
		}
		$file = $file && $this->config['dir'] ? $this->config['dir'].$file : $file;
		$data = $this->auth('DELETE',$file,'','text/html');
		
		$file = $data['file'];
		$headers = array(
			'Authorization: OSS '.$this->config['id'].':'.$data['token'],
			'Date: '.$data['date'],
			'Content-Type: text/html',
		);
		$data = $this->Aliyun_curl($data['ossurl'],'DELETE',$headers,5);

		if($data['status']['http_code'] =='204'){
			$this->error = 1;
			return $file;
		}elseif($data['status']['http_code'] =='404'){
			return false;
			$this->error = 1;
		}elseif($data['status']['http_code'] =='403'){
			return false;
			$this->error = 1;
		}
	}
	
	function Aliyun_curl($url,$type,$headers,$data){
		if($this->error) {
			return array();
		}
		$url = trim($url);
		if(!in_array($type,array('PUT','DELETE','HEAD')) || !$url){
			return array();
		}
		
		$ch = curl_init();  
		curl_setopt($ch, CURLOPT_USERAGENT, 'Slimbbs/1.0.1'); //定义USERAGENT Slimbbs
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FILETIME, true);
		curl_setopt($ch, CURLOPT_FRESH_CONNECT, false);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_NOSIGNAL, true);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		
		if($headers){
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		}
		switch ($type){
			case 'PUT' :
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
				if($this->filesize){
					curl_setopt ($ch, CURLOPT_INFILESIZE, $this->filesize);
					curl_setopt ($ch, CURLOPT_INFILE, $this->file);
					curl_setopt ($ch, CURLOPT_UPLOAD, true);
				}
				break;
				 
			case 'DELETE':
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
				break; 
				
			case 'HEAD':
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
				curl_setopt($ch, CURLOPT_NOBODY, 1);
				break; 
			 
		}  
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		curl_close($ch); 
		$return = array('status'=>$status,'data'=>$data,'errno'=>$errno);
		unset($data,$status,$errno);
		return $return;  
	}
	
	function connect() {
		return true;
	}

	function set_error($code = 0) {
		$this->_error = $code;
	}

	function error() {
		return $this->_error;
	}

	function clear($str) {
		return str_replace(array( "\n", "\r", '..'), '', $str);
	}

	function ftp_connect($ftphost, $username, $password, $ftppath, $ftpport = 21, $timeout = 30, $ftpssl = 0, $ftppasv = 0) {
		return;

	}
	
	function set_option($cmd, $value) {
		return;
	}

	function ftp_mkdir($directory) {
		return;
	}

	function ftp_rmdir($directory) {
		return;
	}

	function ftp_put($remote_file, $local_file, $mode = FTP_BINARY) {
		return;
	}

	function ftp_fput($remote_file, $sourcefp, $mode = FTP_BINARY) {
		return;
	}

	

	function ftp_close() {
	}

	function ftp_get($local_file, $remote_file, $mode, $resumepos = 0) {
		return;
	}

	function ftp_login($username, $password) {
		return;
	}

	function ftp_pasv($pasv) {
		return;
	}

	function ftp_chdir($directory) {
		return;
	}

	function ftp_site($cmd) {
		return;
	}

	function ftp_chmod($filename, $mod = 0777) {
		return;
	}

	function ftp_pwd() {
		return;
	}
	
	
	
	function get_mime($ext){
		$mime_types = array ( 'apk' => 'application/vnd.android.package-archive', '3gp' => 'video/3gpp', 'ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'asc' => 'text/plain', 'atom' => 'application/atom+xml', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', 'bmp' => 'image/bmp', 'cdf' => 'application/x-netcdf', 'cgm' => 'image/cgm', 'class' => 'application/octet-stream', 'cpio' => 'application/x-cpio', 'cpt' => 'application/mac-compactpro', 'csh' => 'application/x-csh', 'css' => 'text/css', 'dcr' => 'application/x-director', 'dif' => 'video/x-dv', 'dir' => 'application/x-director', 'djv' => 'image/vnd.djvu', 'djvu' => 'image/vnd.djvu', 'dll' => 'application/octet-stream', 'dmg' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'dtd' => 'application/xml-dtd', 'dv' => 'video/x-dv', 'dvi' => 'application/x-dvi', 'dxr' => 'application/x-director', 'eps' => 'application/postscript', 'etx' => 'text/x-setext', 'exe' => 'application/octet-stream', 'ez' => 'application/andrew-inset', 'flv' => 'video/x-flv', 'gif' => 'image/gif', 'gram' => 'application/srgs', 'grxml' => 'application/srgs+xml', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'hdf' => 'application/x-hdf', 'hqx' => 'application/mac-binhex40', 'htm' => 'text/html', 'html' => 'text/html', 'ice' => 'x-conference/x-cooltalk', 'ico' => 'image/x-icon', 'ics' => 'text/calendar', 'ief' => 'image/ief', 'ifb' => 'text/calendar', 'iges' => 'model/iges', 'igs' => 'model/iges', 'jnlp' => 'application/x-java-jnlp-file', 'jp2' => 'image/jp2', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'application/x-javascript', 'kar' => 'audio/midi', 'latex' => 'application/x-latex', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'm3u' => 'audio/x-mpegurl', 'm4a' => 'audio/mp4a-latm', 'm4p' => 'audio/mp4a-latm', 'm4u' => 'video/vnd.mpegurl', 'm4v' => 'video/x-m4v', 'mac' => 'image/x-macpaint', 'man' => 'application/x-troff-man', 'mathml' => 'application/mathml+xml', 'me' => 'application/x-troff-me', 'mesh' => 'model/mesh', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mif' => 'application/vnd.mif', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpga' => 'audio/mpeg', 'ms' => 'application/x-troff-ms', 'msh' => 'model/mesh', 'mxu' => 'video/vnd.mpegurl', 'nc' => 'application/x-netcdf', 'oda' => 'application/oda', 'ogg' => 'application/ogg', 'ogv' => 'video/ogv', 'pbm' => 'image/x-portable-bitmap', 'pct' => 'image/pict', 'pdb' => 'chemical/x-pdb', 'pdf' => 'application/pdf', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'pic' => 'image/pict', 'pict' => 'image/pict', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'pnt' => 'image/x-macpaint', 'pntg' => 'image/x-macpaint', 'ppm' => 'image/x-portable-pixmap', 'ppt' => 'application/vnd.ms-powerpoint', 'ps' => 'application/postscript', 'qt' => 'video/quicktime', 'qti' => 'image/x-quicktime', 'qtif' => 'image/x-quicktime', 'ra' => 'audio/x-pn-realaudio', 'ram' => 'audio/x-pn-realaudio', 'ras' => 'image/x-cmu-raster', 'rdf' => 'application/rdf+xml', 'rgb' => 'image/x-rgb', 'rm' => 'application/vnd.rn-realmedia', 'roff' => 'application/x-troff', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'silo' => 'model/mesh', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'smi' => 'application/smil', 'smil' => 'application/smil', 'snd' => 'audio/basic', 'so' => 'application/octet-stream', 'spl' => 'application/x-futuresplash', 'src' => 'application/x-wais-source', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'svg' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash', 't' => 'application/x-troff', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'tr' => 'application/x-troff', 'tsv' => 'text/tab-separated-values', 'txt' => 'text/plain', 'ustar' => 'application/x-ustar', 'vcd' => 'application/x-cdlink', 'vrml' => 'model/vrml', 'vxml' => 'application/voicexml+xml', 'wav' => 'audio/x-wav', 'wbmp' => 'image/vnd.wap.wbmp', 'wbxml' => 'application/vnd.wap.wbxml', 'webm' => 'video/webm', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wrl' => 'model/vrml', 'xbm' => 'image/x-xbitmap', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xls' => 'application/vnd.ms-excel', 'xml' => 'application/xml', 'xpm' => 'image/x-xpixmap', 'xsl' => 'application/xml', 'xslt' => 'application/xslt+xml', 'xul' => 'application/vnd.mozilla.xul+xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'zip' => 'application/zip', 'pps' => 'application/vnd.ms-powerpoint', 'odt' => 'application/vnd.oasis.opendocument.text', 'tgz' => 'application/x-gzip', 'bz' => 'application/x-bzip2', 'bz2' => 'application/x-bzip2', 'tbz' => 'application/x-bzip2', 'rar' => 'application/x-rar', '7z' => 'application/x-7z-compressed', 'php' => 'text/x-php', 'rtfd' => 'text/rtfd', 'py' => 'text/x-python', 'java' => 'text/x-java-source', 'rb' => 'text/x-ruby', 'pl' => 'text/x-perl', 'sql' => 'text/x-sql', 'tga' => 'image/x-targa', 'psd' => 'image/vnd.adobe.photoshop', 'mp4a' => 'audio/mp4', 'wma' => 'audio/x-ms-wma', 'wm' => 'video/x-ms-wmv', 'mkv' => 'video/x-matroska');
		if($mime_types[$ext]){
			return $mime_types[$ext];
		}else{
			return ;
		}
	}
}